<template>
  <el-select
    :value="value"
    v-el-select-loadmore:rangeNum="loadMore(numbers)"
    @change="getChange"
    @input="$emit('input', $event)"
    :loading="loading"
    reserve-keyword
    clearable
    ref="select"
    @clear="clear"
    :disabled="selectDisabled"
    :remote-method="
      query => {
        remoteMethod(query, value);
      }
    "
    filterable
    placeholder="请选择"
    remote
    :size="selectSize"
    style="width: 100%"
    @visible-change="visibleChange"
  >
    <el-option
      v-for="item in originalOptions.slice(0, numbers)"
      :key="item.companyId"
      :label="item.companyName"
      :value="item.companyId"
    />
  </el-select>
</template>

<script>
export default {
  name: "segmentSelection",
  directives: {
    "el-select-loadmore": {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector(
          ".el-select-dropdown .el-select-dropdown__wrap"
        );
        SELECTWRAP_DOM.addEventListener("scroll", function() {
          /**
           * scrollHeight 获取元素内容高度(只读)
           * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
           * clientHeight 读取元素的可见高度(只读)
           * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
           * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
           */
          const condition =
            this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (condition) binding.value();
        });
      }
    }
  },
  props: {
    //组件size
    selectSize: {
      type: String,
      default: "mini"
    },
    //组件options
    options: {
      type: Array,
      default: () => {
        return [];
      }
    },
    //传入的数据
    value: {
      type: [String, Number, Array]
    },
    //是否禁用
    selectDisabled: {
      type: Boolean,
      default: false
    }
  },
  //使用监听器监听传入的options,赋值给originalOptions
  watch: {
    options: {
      handler(val) {
        this.initOptions(this.value);
      },
      deep: true
    },
    //监听所选项变化，进行搜索回显/或初始化列表数据并回显
    value(val) {
      // console.log(val, "监听所选项变化，进行搜索回显/或初始化列表数据并回显");
      this.initOptions(this.value);
    }
  },
  data() {
    return {
      queryText: "", //默认搜索项
      loading: false, //搜索loading
      numbers: 20, //默认显示列表数量
      indexItem: 0,
      originalOptions: [] //下拉列表数据
    };
  },
  methods: {
    clear() {
      this.remoteMethod("", this.value);
    },
    // 下拉框显示/隐藏触发，下来框显示初始话值为100
    visibleChange(flag) {
      // console.log(flag, "下拉框显示隐藏");
      if (flag) {
        this.numbers = 20;
        this.initOptions(this.value);
      } else {
        this.queryText =""
        this.$refs.select.query = "";
        this.initOptions(this.value);
      }
    },
    //远程搜索方法
    remoteMethod(query, checkedData) {
      // console.log(query, "远程搜索query");
      // console.log(checkedData, "远程搜索checkedData");
      this.queryText = query;
      this.loading = true;
      let arr = [];
      setTimeout(() => {
        if (query !== "") {
          //从完整数据中筛选所匹配项
          arr = this.options.filter(item => {
            return (
              item.companyName.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
          });
        } else {
          arr = this.options;
        }
        if (arr.length == 0) {
          this.originalOptions = [];
        } else {
          this.originalOptions = [...arr];
        }
        this.loading = false;
      }, 80);
    },
    initOptions(arr) {
      this.options.forEach((item, index) => {
        if (this.options.length <= 20) {
          this.indexItem = 0;
          // this.numbers = 0;
        } else {
          if (item.companyId == arr) {
            if (index + 20 >= this.options.length) {
              this.indexItem = this.options.length - 20;
              this.numbers = this.options.length - 20;
            } else {
              this.indexItem = index;
              this.numbers = index;
            }
          }
        }
      });
      this.originalOptions = [...this.options.slice(this.indexItem)];
    },
    // 解决回显时显示为id的问题
    // initSelectData(arr) {
    //   // console.log(arr,"解决回显时显示为id的问题");
    //   return this.options.filter(item => arr === item.companyId); // 选中的值 数组
    // },
    // 下拉框滚动触发添加待选数据
    loadMore(n) {
      //n是默认初始展示的条数会在渲染的时候就可以获取,具体可以打log查看
      return () => (this.numbers += 20); //每次滚动到底部可以新增条数  可自定义
    },
    getChange(val) {
      this.$emit("getChange", val);
    }
  },
  mounted() {
    // this.originalOptions = this.options;
    this.initOptions(this.value);
  }
};
</script>

<style scoped></style>
